package fr.inserm.u915.tabixserver;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;

public class TabixCtxListener  implements ServletContextListener
	{
	static private final Logger LOG=Logger.getLogger("tabix");
	public static final String TABIX_MODEL_ATTRIBUTE="tabix.server.model";
	@Override
	public void contextInitialized(ServletContextEvent event)
		{
		ServletContext ctx=event.getServletContext();
		//date
		DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		Date date = new Date();
		ctx.setAttribute("deploy.time", dateFormat.format(date));
		
	
		
		try {
			/* read the properties */
			String param=ctx.getInitParameter("model.path");
			if(param==null) throw new ServletException("init param missing \"model.path\"");
			ModelFactory modelFactory=new ModelFactory();
			Model model=modelFactory.parse(new File(param));
			/* put it in context */
			ctx.setAttribute(TABIX_MODEL_ATTRIBUTE, model);
			
		
			//LOG level
			param=ctx.getInitParameter("log.level");
			if(param!=null)
				{
				try
					{
					Level level=Level.parse(param.trim());
					LOG.setLevel(level);
					}
				catch(Throwable err2)
					{
					//ignore
					}
				}
			}
		catch (Throwable e)
			{
			LOG.info("error in config "+e.getMessage());
			ctx.setAttribute(ConfigErrorFilter.CONFIG_ERROR, e);
			}
		
		}
	
	@Override
	public void contextDestroyed(ServletContextEvent event)
		{
		ServletContext ctx=event.getServletContext();
		ctx.removeAttribute(TABIX_MODEL_ATTRIBUTE);
		}

}
